//Author Rahul Ashok for SUTD//Author Rahul Ashok for SUTD//Author Rahul Ashok for SUTD

package fllab.com.service;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;

import org.apache.tomcat.util.http.fileupload.FileUtils;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import org.apache.tomcat.*;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;

import com.mysql.jdbc.PreparedStatement;

import flab.com.exception.LightException;
import fllab.com.entitiy.ItemEntity;
import fllab.com.entitiy.LightEntity;


public class FLabService {
	
	
	public List<LightEntity> getLightDetails(int selectedMote) throws LightException, ClassNotFoundException {
		
		//LightEntity lE = new LightEntity();
	int light;
		String sm = "ZBTM00" + selectedMote;
		EntityManager em=null;
		try{
			//Class.forName("com.mysql.jdbc.Driver");
			System.out.println("In Service 1");
			EntityManagerFactory emf=Persistence.createEntityManagerFactory("FLLab");
			em=emf.createEntityManager();
			em.getTransaction().begin();
			
			Query q = em.createQuery("select a.reading from LightEntity a where a.primary_key= (select MAX(b.primary_key) from LightEntity b where b.device_id = ?1 and b.task = 2) and a.device_id=?2"); 
			System.out.println("In Service 2");
			
			q.setParameter(1, sm);
			q.setParameter(2, sm);
			
			List<LightEntity> list = q.getResultList();
			
			if(list.size()==0){
				throw new LightException();
			}
			System.out.println("In Service 4");
			return list;
					
		}
		finally{
			if(em!=null){
				em.close();
			}
			
		}
		
	
	}
	
	
public List<LightEntity> getDateDetails(int selectedMote) throws LightException, ClassNotFoundException {
		
		//LightEntity lE = new LightEntity();
	int light;
		String sm = "ZBTM00" + selectedMote;
		EntityManager em=null;
		try{
			//Class.forName("com.mysql.jdbc.Driver");
			System.out.println("In Service 1");
			EntityManagerFactory emf=Persistence.createEntityManagerFactory("FLLab");
			em=emf.createEntityManager();
			em.getTransaction().begin();
			
			Query q = em.createQuery("select a.device_date from LightEntity a where a.primary_key= (select MAX(b.primary_key) from LightEntity b where b.device_id = ?1) and a.device_id=?2"); 
			System.out.println("In Service 2");
			
			q.setParameter(1, sm);
			q.setParameter(2, sm);
			
			List<LightEntity> list = q.getResultList();
			
			if(list.size()==0){
				throw new LightException();
			}
			System.out.println("In Service 4");
			return list;
					
		}
		finally{
			if(em!=null){
				em.close();
			}
			
		}
		
	
	}
	
	

public List<LightEntity> getTimeDetails(int selectedMote) throws LightException, ClassNotFoundException {
	
	//LightEntity lE = new LightEntity();
int light;
	String sm = "ZBTM00" + selectedMote;
	EntityManager em=null;
	try{
		//Class.forName("com.mysql.jdbc.Driver");
		System.out.println("In Service 1");
		EntityManagerFactory emf=Persistence.createEntityManagerFactory("FLLab");
		em=emf.createEntityManager();
		em.getTransaction().begin();
		
		Query q = em.createQuery("select a.device_time from LightEntity a where a.primary_key= (select MAX(b.primary_key) from LightEntity b where b.device_id = ?1) and a.device_id=?2"); 
		System.out.println("In Service 2");
		
		q.setParameter(1, sm);
		q.setParameter(2, sm);
		
		List<LightEntity> list = q.getResultList();
		
		if(list.size()==0){
			throw new LightException();
		}
		System.out.println("In Service 4");
		return list;
				
	}
	finally{
		if(em!=null){
			em.close();
		}
		
	}
	

}


public List<LightEntity> getHumidityDetails(int selectedMote) throws LightException, ClassNotFoundException {
	
	//LightEntity lE = new LightEntity();
int light;
	String sm = "ZBTM00" + selectedMote;
	EntityManager em=null;
	try{
		//Class.forName("com.mysql.jdbc.Driver");
		System.out.println("In Service 1");
		EntityManagerFactory emf=Persistence.createEntityManagerFactory("FLLab");
		em=emf.createEntityManager();
		em.getTransaction().begin();
		
		Query q = em.createQuery("select a.reading from LightEntity a where a.primary_key= (select MAX(b.primary_key) from LightEntity b where b.device_id = ?1 and b.task = 4) and a.device_id=?2"); 
		System.out.println("In Service 2");
		
		q.setParameter(1, sm);
		q.setParameter(2, sm);
		
		List<LightEntity> list = q.getResultList();
		
		if(list.size()==0){
			throw new LightException();
		}
		System.out.println("In Service 4");
		return list;
				
	}
	finally{
		if(em!=null){
			em.close();
		}
		
	}
	

}


public List<LightEntity> getTempDetails(int selectedMote) throws LightException, ClassNotFoundException {
	
	//LightEntity lE = new LightEntity();
int light;
	String sm = "ZBTM00" + selectedMote;
	EntityManager em=null;
	try{
		//Class.forName("com.mysql.jdbc.Driver");
		System.out.println("In Service 1");
		EntityManagerFactory emf=Persistence.createEntityManagerFactory("FLLab");
		em=emf.createEntityManager();
		em.getTransaction().begin();
		
		Query q = em.createQuery("select a.reading from LightEntity a where a.primary_key= (select MAX(b.primary_key) from LightEntity b where b.device_id = ?1 and b.task = 1) and a.device_id=?2"); 
		System.out.println("In Service 2");
		
		q.setParameter(1, sm);
		q.setParameter(2, sm);
		
		List<LightEntity> list = q.getResultList();
		
		if(list.size()==0){
			throw new LightException();
		}
		System.out.println("In Service 4");
		return list;
				
	}
	finally{
		if(em!=null){
			em.close();
		}
		
	}
	

}

public List<LightEntity> getSoundDetails(int selectedMote) throws LightException, ClassNotFoundException {
	
	//LightEntity lE = new LightEntity();
int light;
	String sm = "ZBTM00" + selectedMote;
	EntityManager em=null;
	try{
		//Class.forName("com.mysql.jdbc.Driver");
		System.out.println("In Service 1");
		EntityManagerFactory emf=Persistence.createEntityManagerFactory("FLLab");
		em=emf.createEntityManager();
		em.getTransaction().begin();
		
		Query q = em.createQuery("select a.reading from LightEntity a where a.primary_key= (select MAX(b.primary_key) from LightEntity b where b.device_id = ?1 and b.task = 5) and a.device_id=?2"); 
		System.out.println("In Service 2");
		
		q.setParameter(1, sm);
		q.setParameter(2, sm);
		
		List<LightEntity> list = q.getResultList();
		
		if(list.size()==0){
			throw new LightException();
		}
		System.out.println("In Service 4");
		return list;
				
	}
	finally{
		if(em!=null){
			em.close();
		}
		
	}
	

}

	
	public void start() throws Exception
    {
        URL url = new URL("http://192.168.81.1:3480/data_request?id=lu_action&DeviceNum=19&serviceId=urn:upnp-org:serviceId:SwitchPower1&action=SetTarget&newTargetValue=1");
        URLConnection connection = url.openConnection();

        Document doc = parseXML(connection.getInputStream());
        NodeList descNodes = doc.getElementsByTagName("JobID");

        for(int i=0; i<descNodes.getLength();i++)
        {
            System.out.println(descNodes.item(i).getTextContent());
        }
    }
	
	public String usage() throws Exception
    {
		
		
		String iL="default";
		
		  URL oracle = new URL("http://192.168.81.1:3480/data_request?id=variableget&DeviceNum=19&serviceId=urn:micasaverde-com:serviceId:EnergyMetering1&Variable=Watts");
	        BufferedReader in = new BufferedReader(
	        new InputStreamReader(oracle.openStream()));

	        String inputLine;
	        while ((inputLine = in.readLine()) != null)
	            {
	        	System.out.println(inputLine);
	        	iL=inputLine;
	            }
	        in.close();
	        System.out.println(iL);
	        return iL;
	       

    }
    
	
	public String usage2() throws Exception
    {
		String iL="default";
		
		  URL oracle = new URL("http://192.168.81.1:3480/data_request?id=variableget&DeviceNum=24&serviceId=urn:micasaverde-com:serviceId:EnergyMetering1&Variable=Watts");
	        BufferedReader in = new BufferedReader(
	        new InputStreamReader(oracle.openStream()));

	        String inputLine;
	        while ((inputLine = in.readLine()) != null)
	            {
	        	System.out.println(inputLine);
	        	iL=inputLine;
	            }
	        in.close();
	        System.out.println(iL);
	        return iL;

    }
	
	public void start1() throws Exception
    {
        URL url = new URL("http://192.168.81.1:3480/data_request?id=lu_action&DeviceNum=19&serviceId=urn:upnp-org:serviceId:SwitchPower1&action=SetTarget&newTargetValue=0");
        URLConnection connection = url.openConnection();

        Document doc = parseXML(connection.getInputStream());
        NodeList descNodes = doc.getElementsByTagName("JobID");

        for(int i=0; i<descNodes.getLength();i++)
        {
            System.out.println(descNodes.item(i).getTextContent());
        }
    }

	public void start2() throws Exception
    {
        URL url = new URL("http://192.168.81.1:3480/data_request?id=lu_action&DeviceNum=24&serviceId=urn:upnp-org:serviceId:SwitchPower1&action=SetTarget&newTargetValue=1");
        URLConnection connection = url.openConnection();

        Document doc = parseXML(connection.getInputStream());
        NodeList descNodes = doc.getElementsByTagName("JobID");

        for(int i=0; i<descNodes.getLength();i++)
        {
            System.out.println(descNodes.item(i).getTextContent());
        }
    }
	
	public void start3() throws Exception
    {
        URL url = new URL("http://192.168.81.1:3480/data_request?id=lu_action&DeviceNum=24&serviceId=urn:upnp-org:serviceId:SwitchPower1&action=SetTarget&newTargetValue=0");
        URLConnection connection = url.openConnection();

        Document doc = parseXML(connection.getInputStream());
        NodeList descNodes = doc.getElementsByTagName("JobID");

        for(int i=0; i<descNodes.getLength();i++)
        {
            System.out.println(descNodes.item(i).getTextContent());
        }
    }
    public Document parseXML(InputStream stream)
    throws Exception
    {
        DocumentBuilderFactory objDocumentBuilderFactory = null;
        DocumentBuilder objDocumentBuilder = null;
        Document doc = null;
        try
        {
            objDocumentBuilderFactory = DocumentBuilderFactory.newInstance();
            objDocumentBuilder = objDocumentBuilderFactory.newDocumentBuilder();

            doc = objDocumentBuilder.parse(stream);
        }
        catch(Exception ex)
        {
            throw ex;
        }       

        return doc;
    }
	
	
		
	
	
public int addToDatabase1(String name){
		
		EntityManager em=null;
		try{
			
			//Connection dbConnection;
			java.util.Date dt = new java.util.Date();
			
        java.text.SimpleDateFormat stf = 
    		    new java.text.SimpleDateFormat("HH:mm:ss");
        String time = stf.format(dt);
    	
     		
			System.out.println("In Service");
			EntityManagerFactory emf=Persistence.createEntityManagerFactory("FLLab");
			em=emf.createEntityManager();
			em.getTransaction().begin();
			
						
			System.out.println("In Service 1");
			ItemEntity itemEntity= new ItemEntity();
			
		
			//itemEntity.setP_key(count1);
			itemEntity.setTime(time);
			itemEntity.setName(name);
			itemEntity.setLabel("Stop");
			System.out.println("In Service 2");
			em.persist(itemEntity);
			
			System.out.println("In Service 3");
			em.getTransaction().commit();
			System.out.println("In Service 4");
			return 1;			
		}
		finally{
			if(em!=null){
				em.close();
			}	
		}
		
	}
	

public int addToDatabase_Generic(String value, String name){
	
	EntityManager em=null;
	try{
		
		//Connection dbConnection;
		java.util.Date dt = new java.util.Date();
		
    java.text.SimpleDateFormat stf = 
		    new java.text.SimpleDateFormat("HH:mm:ss");
    String time = stf.format(dt);
	
 		
		System.out.println("In Service");
		EntityManagerFactory emf=Persistence.createEntityManagerFactory("FLLab");
		em=emf.createEntityManager();
		em.getTransaction().begin();
		
					
		System.out.println("In Service 1");
		ItemEntity itemEntity= new ItemEntity();
		
	
	
		itemEntity.setTime(time);
		itemEntity.setName(name);
		itemEntity.setLabel(value);
		System.out.println("In Service 2");
		em.persist(itemEntity);
		
		System.out.println("In Service 3");
		em.getTransaction().commit();
		System.out.println("In Service 4");
		return 1;			
	}
	finally{
		if(em!=null){
			em.close();
		}	
	}
	
}


public int addToDatabase(String name){
		
		EntityManager em=null;
		try{
			
			java.util.Date dt = new java.util.Date();
			java.text.SimpleDateFormat sdf = 
    		    new java.text.SimpleDateFormat("yyyy-MM-dd");

        java.text.SimpleDateFormat stf = 
    		    new java.text.SimpleDateFormat("HH:mm:ss");
        String time = stf.format(dt);
    	
        String date = sdf.format(dt);
			
			System.out.println("In Service");
			EntityManagerFactory emf=Persistence.createEntityManagerFactory("FLLab");
			em=emf.createEntityManager();
			em.getTransaction().begin();
			
			System.out.println("In Service 1");
			ItemEntity itemEntity= new ItemEntity();
			
			itemEntity.setTime(time);
			itemEntity.setName(name);
			itemEntity.setLabel("Start");
			System.out.println("In Service 2");
			em.persist(itemEntity);
			System.out.println("In Service 3");
			em.getTransaction().commit();
			System.out.println("In Service 4");
			return 1;			
		}
		finally{
			if(em!=null){
				em.close();
			}	
		}
		
	}
	
	

	
	
	
	
	
	
	
	
}
